import os

from datetime import timedelta
import datetime
import environ
from os.path import abspath, dirname, join
from decouple import config

env = environ.Env()


def root(*dirs):
    base_dir = join(dirname(__file__), '../..', '..')
    return abspath(join(base_dir, *dirs))


BASE_DIR = root()

SECRET_KEY = config('SECRET_KEY')

DEBUG = True

ALLOWED_HOSTS = ['*']

# Application definition

SHARED_APPS = (
    'django_tenants',  # mandatory

    'django.contrib.contenttypes',

    # everything below here is optional
    'django.contrib.auth',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.admin',
    'corsheaders',
    'apps.users',
    'apps.core',
    'apps.location',
    'apps.worker'
)

TENANT_APPS = (
    # your tenant-specific apps
    'apps.tenant',
    'apps.client',
    'apps.notification',
    'apps.document',
    'apps.communication',
    'apps.payment',
    'apps.booking',
    'apps.billing',
    'apps.subscription',
)

INSTALLED_APPS = list(SHARED_APPS) + [app for app in TENANT_APPS if app not in SHARED_APPS]

TENANT_MODEL = "users.Provider"  # app.Model
TENANT_DOMAIN_MODEL = "users.Domain"  # app.Model

PUBLIC_SCHEMA_DOMAIN = 'localhost'
PUBLIC_DOMAIN = 'localhost'

AUTH_USER_MODEL = 'users.User'


MIDDLEWARE = [
    # 'django_tenants.middleware.main.TenantMainMiddleware',
    'core.tenant_middleware.TenantMainMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
]


ROOT_URLCONF = 'ethera.urls'

PGCRYPTO_KEY = config('PGCRYPTO_KEY')

CORS_ORIGIN_ALLOW_ALL = True

USE_TZE = False

APPEND_SLASH = False

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.request',

            ],
        },
    },
]

WSGI_APPLICATION = 'ethera.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django_tenants.postgresql_backend',
        'HOST': config('DEV_DATABASE_HOST'),
        'NAME': config('DEV_DATABASE_NAME'),
        'USER': config('DEV_DATABASE_USERNAME'),
        'PASSWORD': config('DEV_DATABASE_PASSWORD'),
    }
}


DATABASE_ROUTERS = (
    'django_tenants.routers.TenantSyncRouter',
)

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(days=1),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=8),
    'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': True,
    'UPDATE_LAST_LOGIN': False,

    'ALGORITHM': 'HS256',
    'SIGNING_KEY': SECRET_KEY,
    'VERIFYING_KEY': None,
    'AUDIENCE': None,
    'ISSUER': None,
    'JWK_URL': None,
    'LEEWAY': 0,

    'AUTH_HEADER_TYPES': ('Bearer',),
    'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
    'USER_ID_FIELD': 'id',
    'USER_ID_CLAIM': 'user_id',
    'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule',

    'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
    'TOKEN_TYPE_CLAIM': 'token_type',
    'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser',

    'JTI_CLAIM': 'jti',

    'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
    'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
    'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
    'DEFAULT_FILTER_BACKENDS': [
        'django_filters.rest_framework.DjangoFilterBackend'],
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
    ],
    'PAGE_SIZE': 100,
    'DATETIME_FORMAT': '%s',
    'DATETIME_INPUT_FORMATS': '%s',
    'EXCEPTION_HANDLER': 'lib.ExceptionHandler.global_exception_handler',
}

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Email service: Mailgun
EMAIL_BACKEND = 'lib.django_mailgun.MailgunBackend'
DEFAULT_FROM_EMAIL = config('DEFAULT_FROM_EMAIL')
MAILGUN_SERVER_NAME = config('MAILGUN_SERVER_NAME')
MAILGUN_ACCESS_KEY = config('MAILGUN_ACCESS_KEY')

CONTACT_EMAIL = config('CONTACT_EMAIL')


GCLOUD_PROJECT = config('GCLOUD_PROJECT')
WORKER_SERVICE = config('WORKER_SERVICE')
APPENGINE_DEFAULT_VERSION_HOSTNAME = config('APP_ENGINE_DEFAULT_VERSION_HOSTNAME')

DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage'

GS_EXPIRATION = datetime.timedelta(minutes=10)

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

STATIC_URL = 'static/'

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

LOCKS_UNLOCK_URL = config('LOCKS_UNLOCK_URL')


SHOW_PUBLIC_IF_NO_TENANT_FOUND = True

# PUBLIC_SCHEMA_URL_CONF = "apps.users.urls"
SITE_ID = 1

PROVIDER_URL = config('PROVIDER_URL')
CLIENT_URL = config('CLIENT_URL')
ADMIN_URL = config('ADMIN_URL')


STRIPE_CONNECT_REDIRECT_URL = config('STRIPE_CONNECT_REDIRECT_URL')
STRIPE_SECRET_KEY = config('STRIPE_SECRET_KEY')
SMALLEST_CURRENCY_UNIT = config('SMALLEST_CURRENCY_UNIT')


# GOOGLE TELEHEALTH CONFIGURATION
GOOGLE_CLIENT_ID = config('GOOGLE_CLIENT_ID')
GOOGLE_CLIENT_SECRET = config('GOOGLE_CLIENT_SECRET')
GOOGLE_REDIRECT_URI = config('GOOGLE_REDIRECT_URI')

# ZOOM CONFIGURATION
ZOOM_CLIENT_ID = config('ZOOM_CLIENT_ID')
ZOOM_CLIENT_SECRET = config('ZOOM_CLIENT_SECRET')
ZOOM_REDIRECT_URI = config('ZOOM_REDIRECT_URI')

FCM_FILE_PATH = '/Users/apple/Desktop/Ethera-Tenant/fcm-dev.json'
FCM_KEY = config('FCM_KEY')

TIME_ZONE = 'America/Los_Angeles'
